package com.study.portal.controller.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import sun.misc.BASE64Decoder;

public class ShowImgAction extends ActionSupport {
    private static final long serialVersionUID = -3745357775505359831L;
    
    @Override
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        
        String s = request.getParameter("B64Code");
        BASE64Decoder bd = new BASE64Decoder();
        byte[] byteArr = bd.decodeBuffer(s);
        String filePath = ServletActionContext.getServletContext().getRealPath("/");
        String md5 = encode(byteArr, "md5");
        String picPath = filePath + "\\tmp\\" + md5 + ".gif";
        RandomAccessFile inOut = new RandomAccessFile(picPath, "rw");
        inOut.write(byteArr);
        inOut.close();
        return sendForward(response, request.getContextPath() + "/tmp/" + md5 + ".gif");
       
    }
    private String encode(byte[] data, String algo)
    {
      MessageDigest md = null;
      try {
        md = MessageDigest.getInstance(algo);
        return getHex(md.digest(data), null);
      } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
      }return null;
    }
   
    private String getHex(byte[] buf, String delimiter)
    {
      String result = "";
      if (buf == null) {
        return "";
      }

      String defaultDelimiter = "";
      if ((delimiter != null) && (delimiter.length() > 0)) {
        defaultDelimiter = delimiter;
      }

      for (int i = 0; i < buf.length; i++) {
        if (i > 0) {
          result = result + defaultDelimiter;
        }

        short sValue = buf[i];
        int iValue = 0;
        iValue += sValue;
        String converted = Integer.toHexString(iValue);

        if (converted.length() > 2) {
          converted = converted.substring(converted.length() - 2);
        }
        else if (converted.length() < 2) {
          converted = "0" + converted;
        }

        result = result + converted.toUpperCase();
      }
      return result;
    }


    private String sendForward(HttpServletResponse response, String s)
    {
      response.setContentType("text/xml;charset=UTF-8");
      try
      {
        PrintWriter out = response.getWriter();
        out.write(s);
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }

}
